# -*- coding: utf-8 -*-
import os
import pandas as pd
import matplotlib.pyplot as plt

# ========== 配置路径 ==========
result_dir = '/database/home/duansizhang/hrv_predict/result'
pic_dir    = os.path.join(result_dir, 'pic', 'trend')
os.makedirs(pic_dir, exist_ok=True)

# 1. 读取特征 CSV（假设目录下只有一个 rrfeature CSV）
csv_files = [f for f in os.listdir(result_dir) if f.endswith('_combined_features.csv')]
if not csv_files:
    raise FileNotFoundError("未在结果目录找到任何 '_rrfeature.csv' 文件")
csv_path = os.path.join(result_dir, csv_files[0])
df = pd.read_csv(csv_path)

# 2. 按 timestamp 排序
df = df.sort_values(by='timestamp')

# 3. 要绘制的特征列表（不包括 timestamp，但包含所有你列出的）
features = [
    'mean_nni', 'sdnn', 'sdsd', 'nni_50', 'pnni_50', 'nni_20', 'pnni_20',
    'rmssd', 'median_nni', 'range_nni', 'cvsd', 'cvnni', 'mean_hr',
    'max_hr', 'min_hr', 'std_hr', 'lf', 'hf', 'lf_hf_ratio', 'lfnu',
    'hfnu', 'total_power', 'vlf', 'triangular_index', 'tinn', 'nbeats',
    'sma', 'std_mean', 'peak_total', 'fft_power', 'spec_centroid',
    'spec_flux', 'ApEn', 'sampen'
]

# 4. 循环绘图并保存
for feat in features:
    if feat not in df.columns:
        print(f"警告：'{feat}' 不在 CSV 中，跳过绘图。")
        continue
    plt.figure()
    plt.plot(df['timestamp'], df[feat], marker='o')
    plt.xlabel('Timestamp (s)')
    plt.ylabel(feat)
    plt.title(f'Trend of {feat}')
    plt.grid(True)
    plt.tight_layout()

    out_file = os.path.join(pic_dir, f'{feat}.png')
    plt.savefig(out_file)
    plt.close()

print(f"已生成所有趋势图，保存在：{pic_dir}")
